﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace WebApi.Controllers;

/// <summary>
/// AccountController
/// </summary>
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
public class AccountController : ControllerBase
{
   /* private readonly Logger<AccountController> _logger;
    /// <summary>
    /// AccountController 构造函数
    /// </summary>
    /// <param name="logger"></param>
    public AccountController(Logger<AccountController> logger)
    {
        _logger = logger;
    }*/
    /// <summary>
    /// 登录接口
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="password"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    [HttpPost("login")]
    public  IActionResult Login(string userName, string password, [FromServices] IOptions<JwtOptions> options)
    {
        // 模拟登录逻辑
        if (userName == "admin" && password == "password")
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "wja@microsoft.com"),
                new Claim(ClaimTypes.Role, "Admin"),
                new Claim("CustomClaim", "CustomValue")
            };
            string jwtToken = BuildToken(claims, options.Value);
            //_logger.LogInformation("User {UserName} logged in successfully.", userName);
            return Ok(jwtToken);
        }
        return Unauthorized("Invalid credentials");
    }


    private string BuildToken(List<Claim> claims, JwtOptions jwtOptions)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecretKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(
            issuer: jwtOptions.Issuer,
            audience: jwtOptions.Audience,
            claims: claims,
            expires: DateTime.Now.AddMinutes(jwtOptions.ExpireMinutes),
            signingCredentials: creds
        );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
/// <summary>
/// JWT 配置选项
/// </summary>
public class JwtOptions
{
    /// <summary>
    /// 密钥
    /// </summary>
    public string? SecretKey { get; set; }
    //public int ExpireSeconds { get; set; }
    /// <summary>
    /// 发行者
    /// </summary>
    public string? Issuer { get; set; }
    /// <summary>
    /// 受众
    /// </summary>
    public string? Audience { get; set; }
    /// <summary>
    /// 过期时间（分钟）
    /// </summary>
    public int ExpireMinutes { get; set; }
}